package com.zhangtai.mq.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.rabbitmq.client.Channel;
import com.zhangtai.Neusoft.constVo.EmployeeInfoConst;
import com.zhangtai.Neusoft.dto.SalaryDto;
//import com.zhangtai.Neusoft.service.NeuEmployeeBaseInfoService;
import com.zhangtai.Neusoft.vo.SalaryGroupVo;
import com.zhangtai.exception.RException;
import com.zhangtai.exception.SendErr;
//import com.zhangtai.modules.dao.ssqlDao.EmployeeBaseDao;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.salary.SalaryChangeEntity;
import com.zhangtai.modules.entity.salary.SalaryDistributionEntity;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.salary.SalaryChangeService;
import com.zhangtai.modules.service.salary.SalaryDistributionService;
import com.zhangtai.utils.DateUtils;
import com.zhangtai.utils.NeuAES;
import com.zhangtai.utils.R;
import com.zhangtai.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class EmployeeInfoListener {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${neu.applyUrl}")
    private String neuUrl;

    @Autowired
    private SendErr sendErr;

    @Autowired
    private EmployeeInfoService employeeInfoService;
//    @Autowired
//    private EmployeeBaseDao employeeBaseDao;
    @Autowired
    private SalaryChangeService salaryChangeService;
    @Autowired
    private SalaryDistributionService salaryDistributionService;
//    @Autowired
//    private NeuEmployeeBaseInfoService neuEmployeeBaseInfoService;

//    @RabbitListener(queues = "EMPLOYEE_INFO_QUEUE") //czw本地开发暂时注销
    public void rabbitMqListener(Channel channel, Message message){
        String s = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("监听的消息是:{}", s);
//        如果消息为空，则签收
        if (!StringUtils.isEmpty(s)){
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                e.printStackTrace();

            }
        }

        try {
            JSONObject jsonObject = JSON.parseObject(s);
            String type = jsonObject.getString("type");  //获取类型
            String path = "";
            //1 员工基础信息
            if(EmployeeInfoConst.EMPLOYEE_INFO.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_INFO_URL;
            }//2 员工教育信息
            else if(EmployeeInfoConst.EMPLOYEE_EDUCATION.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_EDUCATION_URL;
            }//3 工作经验
            else if(EmployeeInfoConst.EMPLOYEE_SOCIETY.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_SOCIETY_URL;
            }//4 家庭信息
            else if(EmployeeInfoConst.EMPLOYEE_FAMILY.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_FAMILY_URL;
            }//5 合同信息
            else if(EmployeeInfoConst.EMPLOYEE_CONTRACT.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_CONTRACT_URL;
            }//6党派信息
            else if(EmployeeInfoConst.EMPLOYEE_GROUP.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_GROUP_URL;
            }//7 内部亲属
            else if(EmployeeInfoConst.EMPLOYEE_RELATIVE.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_RELATIVE_URL;
            }//8 薪资组分配
            else if(EmployeeInfoConst.EMPLOYEE_SALARYGROUP.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_SALARYGROUP_URL;
            }//9 奖罚个人
            else if(EmployeeInfoConst.EMPLOYEE_AWARD.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_AWARD_URL;
            }//10薪资确认
            else if(EmployeeInfoConst.EMPLOYEE_SALARY.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_SALARY_URL;
            }//11内部奖惩
            else if(EmployeeInfoConst.EMPLOYEE_INTERNAL_AWARD.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_INTERNAL_AWARD_URL;
            }//删除接口
            else if(EmployeeInfoConst.EMPLOYEE_DEL_EDUCATION.equals(type)
                    ||EmployeeInfoConst.EMPLOYEE_DEL_WORK.equals(type)
                    ||EmployeeInfoConst.EMPLOYEE_DEL_FAMLY.equals(type)
                    ||EmployeeInfoConst.EMPLOYEE_DEL_XZDP.equals(type)
                    ||EmployeeInfoConst.EMPLOYEE_DEL_NHQS.equals(type)
                    ||EmployeeInfoConst.EMPLOYEE_DEL_BUJC.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_DLE_URL;
            }//15 补贴
            else if(EmployeeInfoConst.EMPLOYEE_SUBSIDY.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_SUBSIDY_URL;
            }//16注销薪资组
            else if(EmployeeInfoConst.EMPLOYEE_SALARY_LOGOUT.equals(type)){
                path=EmployeeInfoConst.EMPLOYEE_CANCELL_SALARY_GROUP_URL;
            }
            //薪资信息
            else if(EmployeeInfoConst.EMPLOYEE_GET_SALARY.equals(type)){
                SalaryChangeEntity salaryChangeEntity = jsonObject.getObject("salaryChangeEntity", SalaryChangeEntity.class);
                EmployeeInfoEntity employeeInfoEntity= employeeInfoService.getByIdE(salaryChangeEntity.getOid());
                List<SalaryDto> salaryDtoList= new ArrayList<>();
//                employeeBaseDao.getEmployeeSalaryList(employeeInfoEntity.getCode(),null);
                SalaryChangeEntity entity= salaryChangeService.getByIdE(salaryChangeEntity.getId());
                if(!CollectionUtils.isEmpty(salaryDtoList)&&!ObjectUtils.isEmpty(entity)){
                    SalaryDto salaryDto=salaryDtoList.get(0);
                    //暂时先这样拿
                    entity.setStandardMonthlySalary(getBigDecimal(salaryDto.getTotal()));
                    entity.setBaseSalary(getBigDecimal(salaryDto.getBsalaryBase()));
                    entity.setModuleSalaryBase(getBigDecimal(salaryDto.getMkBases()));
                    salaryChangeService.updateByIdE(entity);
                }
                return;
            }//薪资组信息
            else if(EmployeeInfoConst.EMPLOYEE_GET_SALARY_Z.equals(type)){
                SalaryDistributionEntity salaryDistributionEntity = jsonObject.getObject("salaryDistributionEntity", SalaryDistributionEntity.class);
                EmployeeInfoEntity employeeInfoEntity= employeeInfoService.getByIdE(salaryDistributionEntity.getOid());
                List<SalaryGroupVo> salaryGroupList=new ArrayList<>();
//                employeeBaseDao.getSalaryGroupList(employeeInfoEntity.getCode());
                SalaryDistributionEntity entity= salaryDistributionService.getByIdE(salaryDistributionEntity.getId());
                if(!CollectionUtils.isEmpty(salaryGroupList)&&!ObjectUtils.isEmpty(entity)){
                    SalaryGroupVo salaryGroupVo=salaryGroupList.get(0);
                    entity.setOidSalaryGroupId(Long.valueOf(salaryGroupVo.getGroupId()));
                    entity.setOidPayrollUnitId(Long.valueOf(salaryGroupVo.getPayUnitId()));
                    salaryDistributionService.updateByIdE(entity);
                }
                return;
            }//14保存员工基础和附表信息 获取
            else if(EmployeeInfoConst.EMPLOYEE_INFO_SCHEDULE.equals(type)){
                List<EmployeeInfoEntity> employeeInfoEntityList = jsonObject.getJSONArray("employeeInfoEntityList").toJavaList(EmployeeInfoEntity.class);
                for (EmployeeInfoEntity employeeInfoEntity:employeeInfoEntityList){
//                    neuEmployeeBaseInfoService.saveAndUpdateEmployeeInfoOne(employeeInfoEntity.getCode(),employeeInfoEntity.getOid()+"");
//                    neuEmployeeBaseInfoService.saveEmployeeInfoList(employeeInfoEntity.getCode());
                }
                return;
            }//16 同步合同解除信息
            else if(EmployeeInfoConst.RELIEVE_CONTRACT.equals(type)){
                path=EmployeeInfoConst.RELIEVE_CONTRACT_URL;
            }
            send(jsonObject,path);
        } catch (Exception e) {
            log.error("mq消费者报错\n"+ Arrays.asList(e.getStackTrace()));
            log.error("请求报文是：{}",s);
            String time = DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN);
            ArrayList<StackTraceElement> stackTraceElements = new ArrayList<>();
            for (StackTraceElement stackTraceElement : e.getStackTrace()) {
                if (stackTraceElement.toString().contains("com.zhangtai")){
                    stackTraceElements.add(stackTraceElement);
                }
            }
            sendErr.sendMsg(time+",mq消费者报错:"+e+"\n"+ stackTraceElements);
            throw new RException("mq消费者报错",e);
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private R send(JSONObject jsonObject,String path){
        String token = NeuAES.getToken();
        String url=neuUrl+path;
        jsonObject.put("clientToken",token);
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(jsonObject, httpHeaders);
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        log.info("ehr接口地址{}，请求参数{}",path,jsonObject.toJSONString());
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
        JSONObject body = responseEntity.getBody();
        log.info("ehr接口地址{}，返回结果{}",path,body.toJSONString());
        if (ObjectUtils.isEmpty(body)){
            return R.error();
        }
        Boolean success = body.getBoolean("success");
        if (!success||ObjectUtils.isEmpty(success)){
            log.error("执行方法错误："+body.getString("message"));
            return R.error();
        }
        String message = body.getString("message");
        if (StringUtils.isEmpty(message)){
            return R.error();
        }
        return R.ok();
    }

    private BigDecimal getBigDecimal(String str){
        BigDecimal bigDecimal=new BigDecimal(StringUtils.isEmpty(str)?"0":str);
        return bigDecimal;
    }
}
